from django.shortcuts import render,HttpResponse,reverse
from  users.models import  User

# Create your views here.
def del_user(request,id):
    '''
    删除会员
    :param request:
    :param id:
    :return:
    '''
    try:
        User.objects.get(id=id).delete()
        pass

    except:
       pass
    return  render(request,'del.html')
def index(request):
    '''
    列表页展示所有的用户信息
    :param request:
    :return:
    '''
    users = User.objects.all()
    neirong = {
        'userlist':users
    }
    #获取所有的会员信息并且传值给模板层
    return render(request,'list.html',neirong)
def add_user(request):
    '''
    添加会员
    :param request:
    :return:
    '''
    return  render(request,'add.html')
def edit_user(request,id):
    '''
    编辑会员
    :param request:
    :return:
    '''
    users = User.objects.get(id = id) #获取单个会员信息
    nr = {'user':users}
    return  render(request,'edit.html',nr)
def edit_user_save(request,id):
    '''
    编辑会员(保存）
    :param request:
    :return:
    '''
    jg ='修改成功'
    users = User.objects.get(id = id) #获取单个会员信息
    # 得到用户名、密码、年龄、邮箱
    users.username = request.POST.get('username')
    users.password = request.POST.get('password')
    users.age = request.POST.get('age')
    users.email = request.POST.get('email')
    # 如果修改成功
    try:
        users.save()


    except:
        jg = '修改失败'
    nr = {
        'cz': jg
    }
    return  render(request,'save.html',nr)
def save_user(request):
    '''
    添加会员（数据入库）
    :param request:
    :return:
    '''
    jg = '添加成功'
    username = request.POST.get('username') #用户名
    xingming = request.POST.get('xingming') #姓名
    password = request.POST.get("password") #密码
    age = request.POST.get("age") #年龄
    email = request.POST.get("email") #email
    try:
        # 保存新增会员
        User(username=username, password=password, age=age, email=email,xingming=xingming).save()
    except:
        jg ='添加失败；请联系管理员'
    nr = {
        'cz':jg
    }
    return  render(request,'save.html',nr)
